/*
 * Copyright 2008-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ssn.user.web;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import ssn.common.view.AjaxView;
import ssn.common.web.CommonController;
import ssn.user.service.UserService;
import ssn.user.vo.UserVO;
import egovframework.rte.fdl.cmmn.exception.EgovBizException;
import egovframework.rte.fdl.string.EgovStringUtil;


/**  
 * @Class Name : 
 * @Description : 
 * @Modification Information  
 * @
 * @  수정일      수정자              수정내용
 * @ ---------   ---------   -------------------------------
 * @ 2009.03.16           최초생성
 * 
 * @since 2013. 09.30
 * @version 1.0
 * @see
 */
@SuppressWarnings("rawtypes")
@Controller
public class UserController extends CommonController{
	
    @Resource(name = "userService")
    private UserService userService;

    /**
	 * 글 목록을 조회한다. 
	 * @param 
	 * @param model
	 * @return 
	 * @exception Exception
	 */
    @RequestMapping(value="/user/userList.do")
    public String userList(@ModelAttribute("userVO") UserVO userVO,
    			ModelMap model) throws Exception {
    	
    	/** pageUnit : 페이지 리스트 개수, pageSize : 페이징 개수
    	userVO.setPageUnit(15);
    	userVO.setPageSize(15);
    	*/
    	if(!loginSessionInfo.get().isAdmin()){
    		userVO.setSau_user_id(loginSessionInfo.get().getSsa_admin_id());
    	}else{
    		userVO.setSau_user_id("");
    	}
    	Map resultMap = userService.selectUserList(userVO);
    	List resultList = (List)resultMap.get("resultList");
    	userVO.setTotalRecordCount((Integer)resultMap.get("resultListCnt"));
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("userVO", userVO);
        
        return "/user/userList";
    }
    
    /**
     * 뷰페이지
     * @param userVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/user/userView.do")
    public String userView(@ModelAttribute("userVO") UserVO userVO,
    			ModelMap model) throws Exception {
    	
    	if(EgovStringUtil.isEmpty(userVO.getSau_user_id())){
    		throw new EgovBizException(propertiesService.getString("info.nodata.msg"));
    	}
    	UserVO resultVO = userService.selectUserInfo(userVO);
    	if(resultVO != null){
    		resultVO.setSearchParam(userVO);
    	}
    	
    	model.addAttribute("resultVO", resultVO);
        return "/user/userView";
    }
    
    /**
     * 글쓰기 수정폼
     * @param userVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/user/userWriteForm.do")
    public String userWriteForm(@ModelAttribute("userVO") UserVO userVO,
    			ModelMap model) throws Exception {
    	if(!loginSessionInfo.get().isAdmin()){
    		userVO.setSau_user_id(loginSessionInfo.get().getSsa_admin_id());
    	}
    	if(EgovStringUtil.isNotEmpty(userVO.getSau_user_id())){
    		UserVO resultVO = userService.selectUserInfo(userVO);
    		if(resultVO != null){
        		resultVO.setSearchParam(userVO);
        	}
    		model.addAttribute("resultVO", resultVO);
    	}else{
    		model.addAttribute("resultVO", userVO);
    	}
        return "/user/userWriteForm";
    }
    
    @RequestMapping(value="/user/userSave.do", method=RequestMethod.GET)
    public String userWriteFormGet(ModelMap model) throws Exception {
    	return "redirect:/user/userWriteForm.do";
    }
    
    /**
     * 저장/수정
     * @param userVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/user/userSave.do", method=RequestMethod.POST)
    public String userSave(@ModelAttribute("userVO") @Valid UserVO userVO, BindingResult bindingResult, RedirectAttributes redirectAttr) throws Exception {
    	String returnUrl = "/user/userView.do";
    	if(bindingResult.hasErrors()){
    		for(FieldError error :  bindingResult.getFieldErrors()){
    			redirectAttr.addFlashAttribute("error_"+error.getField(), error.getDefaultMessage());
    		}
    		redirectAttr.addFlashAttribute("tempUrl", propertiesService.getString("file.temp.url"));
    		redirectAttr.addFlashAttribute("userVO", userVO);
    		return "redirect:/user/userWriteForm.do";
    	}
    	if(EgovStringUtil.isNotEmpty(userVO.getSau_user_id()) && userVO.getSau_user_id() != "0"){
    		userService.updateUserInfo(userVO);
    	}else{
    		userService.insertUserInfo(userVO);
    	}
    	if(!loginSessionInfo.get().isAdmin()){
    		returnUrl = "/user/userWriteForm.do";
    		redirectAttr.addFlashAttribute("msg", "수정 되었습니다.");
    	}
    	redirectAttr.addAttribute("sau_user_id", userVO.getSau_user_id());
    	redirectAttr.addAttribute("pageIndex", userVO.getPageIndex());
    	return "redirect:"+returnUrl;
    }
    
    /**
     * 사진 삭제 Ajax
     * @param userVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/user/deleteUserPic.do", method=RequestMethod.POST)
    public ModelAndView deleteUserPic(@RequestParam(value="sau_user_id") String sau_user_id) throws Exception {
    	ModelAndView mav = new ModelAndView(new AjaxView());
    	String result = "false";
    	if(userService.deleteUserPic(sau_user_id))
    		result = "true";
    	mav.addObject("result", result);
    	return mav;
    } 
}
